package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BusiCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据校验统一异常处理
 *
 * @author zhangxueyou
 * @date 2020/9/23-15:18
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e) {
        Map<String, String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((filedErro) -> {
            map.put(filedErro.getField(), filedErro.getDefaultMessage());
        });
        log.error("异常消息{},异常类型{}", e.getMessage(), e.getClass());
        return R.error(BusiCodeEnum.VALID_ARGUMENT.getCode(), BusiCodeEnum.VALID_ARGUMENT.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R unknowExceptionHandle(Throwable e) {
        log.error("异常消息{},异常类型{}", e.getMessage(), e.getClass());
        return R.error(BusiCodeEnum.UN_KNOW_EXCEPTION.getCode(), BusiCodeEnum.UN_KNOW_EXCEPTION.getMsg());
    }
}
